package com.tangding.shiro.realm;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import com.google.common.base.Strings;
import com.tangding.service.entity.role.Role;
import com.tangding.service.entity.user.User;

/**
 * @description 
 *
 * @author Ranger
 * @version 2017年11月9日_上午9:28:18
 *
 */
@Component
public class UserRealm extends AuthorizingRealm implements InitializingBean {
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		final String username = getUsername(principals);

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        
        User user = UserRealmHelper.findUsersByUid(username);
        if (user != null) {
			List<Integer> roleIds = user.getRoles();
			List<Role> roles = UserRealmHelper.getRoles(roleIds);
			if (roles != null && roles.size() > 0) {
				for (Role role : roles) {
					info.addRole(role.getRoleName());
					for (String permission : role.getPermission()) {
						info.addStringPermission(permission);
					}
				}
			}
		}
        return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		 String username = getUsername(token);
		 
        // Null username is invalid
        if (Strings.isNullOrEmpty(username)) {
            throw new AccountException("Null username are not allowed by this realm.");
        }

        User user = UserRealmHelper.findUsersByUid(username);

        SimpleAuthenticationInfo info = null;
        if (user != null) {
        	ByteSource credentialsSalt = ByteSource.Util.bytes(username);
            info = new SimpleAuthenticationInfo(username, user.getPassword(), credentialsSalt, getName());
            Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession();
            session.setAttribute("currentUser", user);
        }

        return info;
	}
	
	protected String getUsername(AuthenticationToken token) {
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        return upToken.getUsername();
    }
	
	protected String getUsername(PrincipalCollection principals) {
        //null usernames are invalid
        if (principals == null) {
            throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
        }

        return (String) getAvailablePrincipal(principals);
    }

	@Override
	public void afterPropertiesSet() throws Exception {
		
	}
}
